import { _decorator, Component, Button, Node, Label, Sprite, Prefab, instantiate } from 'cc';
import { Game } from '../core/Game';
import { Databus } from '../core/Databus';
import { ResourceManager } from '../framework/ResourceManager';
import { SendWebSocket } from '../websocket/SendWebSocket';
import { UniformFunction } from '../platform/UniformFunction';
import { EventManager } from '../core/EventManager';
import { BilliardGame } from './BilliardGame';
import { queryRobotUserList } from '../services/UserInfo';
import { UserAttribute } from '../core/UserAttribute';
import DataEventReport from '../platform/DataEventReport';
import { uniConfig } from '../config/UniConfig';
import { InterstitialAd } from '../platform/ad/InterstitialAd';
const { ccclass, property } = _decorator;

const databus = Databus.Instance();
@ccclass('EndGame')
export class EndGame extends Component {
   // 激励广告弹窗
  @property(Prefab)
  RewordVideoAds: Prefab = null;
  private rewordVideoInstance: Node = null;
  private timestamp = 0;
  private restartMatchButton: Button = null;
  private backHomeButton: Button = null;
  private winResultSprite: Node = null;
  private loseResultSprite: Node = null;
  private endGameLabel: Label = null;
  private winCoin: Node = null;
  onLoad(): void {
    this.restartMatchButton = this.node.getChildByName('RestartButton').getComponent(Button);
    this.backHomeButton = this.node.getChildByName('BackHomeButton').getComponent(Button);
    this.winCoin = this.node.getChildByName('SelfUserComponent').getChildByName('WinCoin');
    this.winResultSprite = this.node.getChildByName('WinResultSprite');
    this.loseResultSprite = this.node.getChildByName('LoseResultSprite');
    this.endGameLabel = this.node.getChildByName('EndLabel').getComponent(Label);
    this.restartMatchButton.node.on(Button.EventType.CLICK, this.restartGame, this);
    this.backHomeButton.node.on(Button.EventType.CLICK, this.backToHomePage, this);
    this.winResultSprite.active = false;
    this.loseResultSprite.active = false;

    EventManager.Instance().AddEventListener('OppoUserLeave', this, this.processOppoUserLeave);
    EventManager.Instance().AddEventListener('EndGameEvent', this, this.onEndGame);
    EventManager.Instance().AddEventListener('StartGame', this, this.onStartGame);

    this.node.active = false;
  }
  start() {
    // this.node.active = false;
    // this.node.getParent().active = false;
  }
  update(deltaTime: number) {
    this.timestamp += 1;
    this.aiUpdateUserStatus();
    this.updateGameEndResult();
    this.updateSelfUserHeader();
    this.updateOppoUserHeader();
    this.updateWinCoin();
    if (Game.Instance().endReason.isSurrender()) {
      this.endGameLabel.string = '游戏结束(主动认输)';
    } else if (Game.Instance().endReason.isTimeout()) {
      this.endGameLabel.string = '游戏结束(超时告负)';
    } else {
      this.endGameLabel.string = '游戏结束';
    }
  }

  public restartGame(button: Button) {
    if (Game.Instance().battleCate.isFancyBattle()) {
      this.leavePage();
      BilliardGame.Instance().startGame();
      return;
    }
    if (!this.checkGoldCoin()) {
      return;
    }
    Game.Instance().playUsers[0].started();
    if (Game.Instance().battleCate.isFrientBattle()) {
      if (Game.Instance().playUsers[1].isLeavedStatus()) {
        new UniformFunction().showInfoToast('对手已离开, 请返回首页', 2000);
      } else {
        new SendWebSocket().userStatus(Game.Instance().playUsers[0]);
        new UniformFunction().showInfoToast('等待对方开始', 2000);
      }
      // 好友对战需要等待对手确认，然后在开始
      // this.node.active = false;
    } else {
      this.node.active = false;
      // 更换对手在开始
      if (!Game.Instance().playUsers[1].isStartedStatus()) {
        const ua = this.matchOppoUser();
        const ext = ResourceManager.Instance().getImageExt(ua.avatarUrl);
        ResourceManager.Instance().loadImageSpriteFrame(
          ResourceManager.OppoUserHeaderImage, ua.avatarUrl, ext
        );
        Game.Instance().setOppoUserAttribute(ua);
      }
      Game.Instance().randomSetSide();
      EventManager.Instance().Emit('RestartGame', {});
    }
  }
  public onStartGame() {
    this.node.getParent().active = false;
    this.node.active = false;
  }
  public onEndGame() {
    this.node.getParent().active = true;
    this.node.active = true;
    DataEventReport.Instance().reportCoreProcess(
      databus.sceneStack.currentPageName(), 'EndGame',
      Game.Instance().battleCate.valueBattle(),
      Game.Instance().gameType.valueType(),
    );

    InterstitialAd.Instance().show();
  }
  public backToHomePage(button: Button) {
    // 开始游戏的时候会隐藏，这里隐藏跳转到首页，会有一段空白间隔
    // this.node.active = false;
    // this.node.getParent().active = false;
    this.leavePage();
    databus.sceneStack.backHomePage();
    Game.Instance().playUsers[0].leaved();
    new SendWebSocket().userStatus(Game.Instance().playUsers[0]);
  }
  public processOppoUserLeave() {
    new UniformFunction().showInfoToast('对手已经离开', 2000);
  }
  private updateGameEndResult() {
    if (Game.Instance().isSelfWin()) {
      this.winResultSprite.active = true;
      this.loseResultSprite.active = false;
    } else {
      this.winResultSprite.active = false;
      this.loseResultSprite.active = true;
    }
  }

  private updateSelfUserHeader() {
    const headSpriteFrame = ResourceManager.Instance().getImageSpriteFrame(ResourceManager.SelfUserHeaderImage);
    if (headSpriteFrame) {
      const userHeader = this.node.getChildByName('SelfUserComponent').getChildByName('UserHeaderImage').getComponent(Sprite);
      userHeader.spriteFrame = headSpriteFrame;
    
      // 更新昵称
      const userName = this.node.getChildByName('SelfUserComponent').getChildByName('UserNickName').getComponent(Label);
      userName.string = Game.Instance().playUsers[0].userAttribute.showNickName();
    }
    const readyStatus = this.node.getChildByName('SelfUserComponent').getChildByName('ReadyStatus');
    readyStatus.active = false;
    if (Game.Instance().playUsers[0].isStartedStatus()) {
      readyStatus.active = true;
    }
  }
  private updateOppoUserHeader() {
    const headSpriteFrame = ResourceManager.Instance().getImageSpriteFrame(ResourceManager.OppoUserHeaderImage);
    if (headSpriteFrame) {
      const userHeader = this.node.getChildByName('OppoUserComponent').getChildByName('UserHeaderImage').getComponent(Sprite);
      userHeader.spriteFrame = headSpriteFrame;

      const userName = this.node.getChildByName('OppoUserComponent').getChildByName('UserNickName').getComponent(Label);
      userName.string = Game.Instance().playUsers[1].userAttribute.showNickName();
    }

    const readyStatus = this.node.getChildByName('OppoUserComponent').getChildByName('ReadyStatus');
    const leaveStatus = this.node.getChildByName('OppoUserComponent').getChildByName('LeaveStatus');
    readyStatus.active = false;
    leaveStatus.active = false;
    if (Game.Instance().playUsers[1].isStartedStatus()) {
      readyStatus.active = true;
      leaveStatus.active = false;
    } else if (Game.Instance().playUsers[1].isLeavedStatus()) {
      readyStatus.active = false;
      leaveStatus.active = true;
    }
  }
  private updateWinCoin() {
    if (Game.Instance().battleCate.isEndlessBattle()) {
      this.winCoin.active = false;
      return;
    }
    if (Game.Instance().battleCate.isFancyBattle()) {
      this.winCoin.active = false;
      return;
    }
    this.winCoin.active = true;
    if (Game.Instance().isSelfWin()) {
      this.winCoin.getChildByName('CoinLabel').getComponent(Label).string = `+${uniConfig.WinCoinValue}`;
    } else {
      this.winCoin.getChildByName('CoinLabel').getComponent(Label).string = `-${uniConfig.WinCoinValue}`;
    }
  }
  private leavePage() {
    this.winResultSprite.active = false;
    this.loseResultSprite.active = false;
  }

  private matchOppoUser() {
    for (var i=0; i<databus.robots.length; i++) {
      if (databus.selfInfo.playLevel.canMatchBattle(databus.robots[i].playLevel.playLevel)) {
        queryRobotUserList(databus.selfInfo.userId, databus.selfInfo.playLevel.playLevel);
        return databus.robots[i];
      }
    }
    if (databus.robots.length > 0) {
      queryRobotUserList(databus.selfInfo.userId, databus.selfInfo.playLevel.playLevel);
      return databus.robots[0];
    }
    queryRobotUserList(databus.selfInfo.userId, databus.selfInfo.playLevel.playLevel);
    return UserAttribute.newDefaultUser();
  }

  private aiUpdateUserStatus() {
    if (!Game.Instance().battleCate.isNetBattle()) {
      return;
    }
    if (this.timestamp === 200) {
      if (Math.random() > 0.5) {
        Game.Instance().playUsers[1].started();
      }
    }
    if (this.timestamp === 800) {
      if (Math.random() > 0.5) {
        Game.Instance().playUsers[1].leaved();
      }
    }
    if (this.timestamp === 1800) {
      Game.Instance().playUsers[1].leaved();
    }
  }

  private checkGoldCoin() {
    if (databus.selfInfo.goldCoin >= 1000) {
      return true;
    }

    databus.rad.adType = 0;
    if (!this.rewordVideoInstance) {
      this.rewordVideoInstance = instantiate(this.RewordVideoAds);
      this.rewordVideoInstance.setParent(this.node);
    }

    this.rewordVideoInstance.active = true;
    // new UniformFunction().showInfoToast('您的金币不足，快来补充吧', 1500);
    return false;
  }
}